﻿Shader "YY/PostProcess/YYBloom"
{
    Properties
    {
        //_MainTex ("Texture", 2D) = "white" {}
    }
	CGINCLUDE
		#include "UnityCG.cginc"
		#include "Include/YYStdLib.cginc"
#include "Include/YYColors.cginc"
#include "Include/YYSampling.cginc"

		sampler2D _MainTex;
		float4 _MainTex_ST;

		float4 _MainTex_TexelSize;
		float4 _Threshold; // x: threshold value (linear), y: threshold - knee, z: knee * 2, w: 0.25 / knee

		sampler2D _BloomTex;
		float _SampleScale;

		float4 _TestParam;

		fixed4 frag(VertexOutputBase i) : SV_Target
		{
			// sample the texture
			fixed4 col = tex2D(_BloomTex, i.texcoord);
			// apply fog
			//UNITY_APPLY_FOG(i.fogCoord, col);
			return col;
			//return fixed4(1, col.g, col.b, col.a);
			//return fixed4(_Threshold.x, 0, 0, 0);
		    //return 
		}

		
	    ///
		half4 Prefilter(half4 color, float2 uv)
		{
			color = QuadraticThreshold(color, _Threshold.x, _Threshold.yzw);
			return color;
		}

		fixed4 FragPrefilter4(VertexOutputBase i) : SV_Target
		{
			half4 color = DownsampleBox4Tap(_MainTex, i.texcoord,_MainTex_TexelSize.xy);
			return Prefilter(SafeHDR(color), i.texcoord);
		}

		half4 FragDownsample4(VertexOutputBase i) : SV_Target
		{
			half4 color = DownsampleBox4Tap(_MainTex, i.texcoord, _MainTex_TexelSize.xy);
			return color;
		}

		half4 Combine(half4 bloom, float2 uv)
		{
			half4 color = tex2D(_BloomTex,uv);
			return bloom * _TestParam.x + color * _TestParam.y;
			//return bloom;
			//return color;
		}

		half4 FragUpsampleBox(VertexOutputBase i) : SV_Target
		{
			half4 bloom = UpsampleBox(_MainTex, i.texcoord, _MainTex_TexelSize.xy, _SampleScale);

			//half4 bloom = tex2D(_MainTex, i.texcoord);

			//return bloom;
			return Combine(bloom, i.texcoord);
		}

	ENDCG

    SubShader
    {
		Cull Off ZWrite Off ZTest Always

        Pass  // 0 
        {
			
            CGPROGRAM
            #pragma vertex VertDefault
            #pragma fragment frag
            ENDCG
        }

		// 1: Prefilter 4 taps
		Pass
		{
			CGPROGRAM
			#pragma vertex VertDefault
			#pragma fragment FragPrefilter4
			ENDCG
		}

		

		// 2 3: Downsample 4 taps
		Pass
		{
			CGPROGRAM
			#pragma vertex VertDefault
			#pragma fragment FragDownsample4
			ENDCG
		}

		

		// 3 5: Upsample box filter
		Pass
		{
			CGPROGRAM

			#pragma vertex VertDefault
			#pragma fragment FragUpsampleBox

			ENDCG
		}


    }
}
